"""
快手视频搜索脚本
用于根据关键词搜索快手视频并提取视频信息
"""

import asyncio
import sys
import os
import json
import re

# Add the project root directory to the Python path
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from playwright.async_api import async_playwright


class KuaishouVideoSearcher:
    """
    快手视频搜索器，用于搜索和提取快手视频信息
    """
    
    def __init__(self):
        """
        初始化快手视频搜索器
        """
        self.playwright = None
        self.context = None
        self.page = None

    async def start_browser(self, headless=False):
        """
        启动浏览器
        """
        self.playwright = await async_playwright().start()
        self.context = await self.playwright.chromium.launch_persistent_context(
            user_data_dir="./user_data/kuaishou",
            channel="chrome",
            headless=headless,
            args=[
                "--no-sandbox",
                "--disable-dev-shm-usage",
                "--disable-blink-features=AutomationControlled",
                "--disable-extensions"
            ],
            viewport={"width": 1920, "height": 1080}
        )
        self.page = await self.context.new_page()
        return self.context, self.page

    async def search_videos(self, keyword, max_count=50):
        """
        搜索快手视频并提取信息
        
        Args:
            keyword (str): 搜索关键词
            max_count (int): 最大获取视频数量
            
        Returns:
            list: 视频信息列表
        """
        # 导航到快手搜索页面，使用正确的参数searchKey
        search_url = f"https://www.kuaishou.com/search/video?searchKey={keyword}"
        await self.page.goto(search_url)
        await self.page.wait_for_timeout(5000)  # 等待页面加载
        
        # 检查是否需要登录
        login_element = await self.page.query_selector("text=登录")
        if login_element:
            print("检测到需要登录，请在浏览器中手动登录...")
            print("注意：如果出现安全验证，请手动完成滑块拼图验证")
            input("登录完成后按回车键继续...")
        
        # 滚动页面以加载更多视频
        videos = []
        scroll_count = 0
        max_scroll_count = max_count // 10 + 5  # 根据需要的视频数量估算滚动次数
        
        while len(videos) < max_count and scroll_count < max_scroll_count:
            # 执行滚动
            await self.page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
            await self.page.wait_for_timeout(3000)  # 等待内容加载
            scroll_count += 1
            
            # 提取当前页面的视频信息
            current_videos = await self.page.evaluate(r'''() => {
                const videos = [];
                // 通过分析页面结构，视频信息在特定的容器中
                const container = document.querySelector('generic[ref="e79"]');
                if (container) {
                    // 获取容器内所有子元素（视频项）
                    const videoItems = Array.from(container.children);
                    
                    videoItems.forEach((item, index) => {
                        if (index >= 100) return; // 只处理前100个视频
                        
                        // 查找标题元素
                        const headingElement = item.querySelector('h5');
                        const title = headingElement ? headingElement.textContent.trim() : '';
                        
                        // 查找点赞数元素
                        const likeElement = Array.from(item.querySelectorAll('*')).find(el => 
                            el.textContent && el.textContent.trim().includes('喜欢')
                        );
                        const likes = likeElement ? likeElement.textContent.trim() : '未知';
                        
                        // 查找链接元素
                        const linkElement = item.closest('a');
                        const url = linkElement ? linkElement.href : '';
                        
                        // 提取photoId
                        const photoId = url ? url.split('/').pop() : '';
                        
                        if (url && title) {
                            videos.push({
                                photo_id: photoId,
                                url: url,
                                title: title,
                                likes: likes
                            });
                        }
                    });
                }
                
                return videos;
            }''')
            
            # 合并视频信息并去重
            for video in current_videos:
                # 检查是否已存在该视频
                if not any(v.get('photo_id') == video.get('photo_id') for v in videos):
                    videos.append(video)
            
            if len(videos) >= max_count:
                break
        
        # 限制返回的视频数量
        return videos[:max_count]
    
    async def close(self):
        """
        关闭浏览器
        """
        if self.context:
            await self.context.close()
        if self.playwright:
            await self.playwright.stop()


async def main():
    """
    主函数，处理命令行参数并执行搜索
    """
    if len(sys.argv) < 2:
        print("使用方法: python kuaishou_video_search.py <关键词> [数量]")
        print("示例: python kuaishou_video_search.py 足球高清 50")
        return
    
    keyword = sys.argv[1]
    max_count = 50  # 默认获取50个视频
    
    if len(sys.argv) > 2:
        try:
            max_count = int(sys.argv[2])
        except ValueError:
            print("数量参数必须是整数，使用默认值50")
    
    print(f"正在搜索关键词: {keyword}, 需要获取 {max_count} 个视频")
    
    # 创建搜索器实例
    searcher = KuaishouVideoSearcher()
    
    try:
        # 启动浏览器
        await searcher.start_browser(headless=False)
        
        # 搜索视频
        videos = await searcher.search_videos(keyword, max_count)
        
        # 输出JSON格式结果
        print(json.dumps(videos, ensure_ascii=False, indent=2))
            
    except Exception as e:
        print(f"搜索过程中发生错误: {e}")
    finally:
        # 关闭浏览器
        await searcher.close()


if __name__ == "__main__":
    asyncio.run(main())